#include <iostream>
#include <vector>
#include <thread>
#include <mutex>
#include <stdexcept>
#include <condition_variable>
#include <atomic>

std::mutex mtx;
std::condition_variable cv;
std::atomic<bool> error_occurred(false); // 使用atomic保证原子操作
std::atomic<int> counter(0); 

void safe_increment(int id) {
    while (true) {
        try {
            std::unique_lock<std::mutex> lock(mtx); // 使用unique_lock以便在等待时解锁
            if (counter >= 5 || error_occurred.load()) {
                // 如果计数器已达上限或已发生错误，则退出循环
                return;
            }
            ++counter; // 增加计数器
            std::cout << "Thread " << id << " incremented counter to " << counter << std::endl;
            if (counter == 3) {
                throw std::runtime_error("Simulated error"); // 模拟一个错误
            }
            lock.unlock(); // 解锁，允许其他线程运行
            std::this_thread::sleep_for(std::chrono::milliseconds(10)); // 延时以减少锁争用
        } catch (const std::runtime_error& e) {
            std::cerr << "Thread " << id << " caught exception: " << e.what() << std::endl;
            error_occurred.store(true); // 更新全局异常标志
            cv.notify_all(); // 通知其他线程异常发生
            return;
        }
    }
}


void watch_for_error(int id) {
    std::unique_lock<std::mutex> lock(mtx);
    while (!error_occurred) {
        cv.wait(lock); // 等待异常发生的通知
    }
    std::cout << "Thread " << id << " noticed an error occurred and is terminating." << std::endl;
}

int main() {
    std::vector<std::thread> threads;
    for (int i = 0; i < 5; ++i) {
        threads.push_back(std::thread(safe_increment, i));
    }
    // 延迟创建监视线程以确保它们不会过早进入等待状态
    for (int i = 5; i < 10; ++i) {
        threads.push_back(std::thread(watch_for_error, i));
    }
    for (auto& th : threads) {
        th.join(); // 等待所有线程完成
    }
    return 0;
}